let forms = [];

$(document).ready(function($){muroj_init()});
muroj_images_preload();

function muroj_init() {
    forms['komento_formo'] = $('.komento-formo');
    $('form').on('submit', muroj_submit);
    $('a[data-ago]').on('click', muroj_post);
    //$('.aldonu-komento a').on('click', muroj_com_form);
    $('.interese a').on('click', muroj_interese);
    $(document).on('siriuso_pagination', function (e, html) {
        let target = $(html);
        target.find('a[data-ago]').on('click', muroj_post);
        //target.find('.aldonu-komento a').on('click', muroj_com_form);
        target.find('.interese a').on('click', muroj_interese);
    })
}

function muroj_images_preload() {
    let images = ['/static/muroj/images/interese_on.png',
        '/static/muroj/images/interese.png'];

    for(let i = 0; i < images.length; i++) {
        let image = new Image();
        image.src = images[i];
    }
}

function muroj_com_form() {
    let btn = $(this);
    let target = btn.parents('div[data-enskribo_id]');

    if(target.children('.komento-formo').length) {
        form = target.children('.komento-formo');
    } else {
        form = forms['komento_formo'].clone().appendTo(target);
        if(form.prop('tagName') === 'FORM') {
            form.append('<input type="hidden" name="enskribo" value="' +
                target.attr('data-enskribo_id') + '">');
            form.on('submit', muroj_submit);
        }
    }

    //Для блока предупреждения
    if(form.hasClass('averto_bloko')) {
        if(form.hasClass('formo-open')) {
            return;
        }
        setTimeout(muroj_toggle_class, 5000, form, 'formo-open');
        setTimeout(muroj_remove_obj, 6000, form);
    }

    setTimeout(muroj_toggle_class, 10, form, 'formo-open');
    if(form.hasClass('formo-open')) {
        setTimeout(muroj_remove_obj, 1010, form);
    }
}

function muroj_toggle_class(obj, class_name) {
    $(obj).toggleClass(class_name);
}

function muroj_remove_obj(obj) {
    if(!$(obj).height() < 1) {
        $(obj).remove();
    }
}

function muroj_get_action(obj) {
    let target = $(obj).find('input[type="hidden"][name="ago"]');

    if(target.length) {
        return target.length > 1 ? target[0].val() : target.val();
    }

    return null;
}

function muroj_submit() {
    let target = $(this);
    let type = muroj_get_action(target);

    switch (type) {
        case 'enskribo':
        case 'komento':
            target.find('input, textarea, select, button').prop('disabled', true);
            toggleBlockForm(target);
            muroj_post(target, type);
            target.find('input, textarea, select, button').prop('disabled', false);
            return false;

        default:
            return true;
    }
}

function muroj_post(form) {
    let data;

    if($(form).prop('tagName') === 'FORM') {
        data = prepare_form(form);
    } else if(form instanceof $.Event) {
        data = prepare_action(form.target);
        let action = $(form.target).attr('data-ago');
        let confirm_string;
        form = $(form.target);
        form = action === 'kom-forigi' ? form.parents('[data-komento_id]')
            : form.parents('[data-enskribo_id]');

        switch (action) {
            case 'kom-forigi':
                confirm_string = l10n.kom_forigi;
                break;

            case 'forigi':
                confirm_string = l10n.forigi;
                break;
            case 'arkivo':
                confirm_string = l10n.arkivo;
                break;
            default:
                break;
        }

        if(confirm_string !== undefined && !confirm(confirm_string)) {
            return;
        }

        toggleBlockForm(form);
    }

    if(data === undefined) {
        console.log('No data for AJAX');
        return;
    }

    $.ajax({
        url: window.location.href,
        type: 'POST',
        async: true,
        data: data,
        cache: false,
        dataType: 'json',
        processData: false,
        contentType: false
    })
        .done(function (result) {
            if(result.status === 'ok') {
                switch (result.type) {
                    case 'enskribo':
                    case 'komento':
                        setTimeout(muroj_insert, 500, result, form);
                        break;

                    case 'arkivo':
                    case 'forigi':
                    case 'restarigi':
                    case 'kom-forigi':
                        if(result.type === 'kom-forigi') {
                            let kom_cnt = form.parents('div[data-enskribo_id]').find('a.aldonu-komento.tuta');
                            let total = parseInt(kom_cnt.text());
                            total = total > 0 ? total - 1 : 0;
                            kom_cnt.text(total);
                        }
                        muroj_before_remove(form);
                        setTimeout(function() {
                            form.toggleClass('muroj_hidden');
                                form.one('transitionend', function() {form.remove()});
                            }, 500);
                        break;

                    default:
                        //setTimeout(function() {form.one('transitionend',
                        //function(){muroj_insert(result); form.remove()})}, 500);
                        break;
                }

                //setTimeout(function(){form.toggleClass('formo-open')}, 500);
            } else {
                if(result.err.__all__ !== undefined) {
                    form.find('.t_bazo_bloko_errors').text(result.err.__all__);
                }

                console.log("Bad server response: " + result.err);
                toggleBlockForm(form);
            }
        })
        .fail(function (jqXHR, textStatus) {
            toggleBlockForm(form);
            console.log("Request failed: " + textStatus);
        });
}

function prepare_form(form) {
    if(typeof form === 'object') {
        out = new FormData();
        fields = $(form).find('input, textarea, select');

        fields.each(function (index, element) {
            let cur = $(element);
            if(cur.prop('type') === 'submit') {
                return;
            } else if(cur.prop('type') === 'checkbox') {
                cur.val(cur.prop('checked'));
            } else if(cur.prop('type') === 'file') {
                let multi = (cur.prop('files').length > 1);
                $.each(cur.prop('files'), function(key, val){
                    out.append(cur.prop('name') + (multi ? ('[' + key + ']') : ''), val);
                });
                return;
            }

            out.append(cur.prop('name'), cur.val());
        });
        out.append('csrfmiddlewaretoken', getCookie('csrftoken'));

        return out;
    }
}

function prepare_action(obj) {
    let target = $(obj);

    if(target.attr('data-ago') !== undefined) {
        let out = new FormData();

        if(target.attr('data-ago') === 'kom-forigi') {
            out.append('komento', target.parents('[data-komento_id]').attr('data-komento_id'))
        } else {
            out.append('enskribo', target.parents('[data-enskribo_id]').attr('data-enskribo_id'));
        }

        out.append('ago', target.attr('data-ago'));
        out.append('csrfmiddlewaretoken', getCookie('csrftoken'));
        return out;
    }
}

function muroj_insert(response, form) {
    let obj = muroj_before_insert(response.html);

    if(form !== undefined) {
        form[0].reset();
        form.find('.t_bazo_bloko_errors').text('');
    }

    toggleBlockForm(form);
    switch (response.type) {
        case 'enskribo':
            $('.t_bazo_bloko_du').last().after(obj);
            break;

        case 'komento':
            let target = $('div[data-enskribo_id=' + response.por_enskribo + ']');
            let total = parseInt(target.find('a.tuta').text()) + 1;
            target.find('.komento-formo').before(obj);
            target.find('a.tuta').text(total);
            break;

        default:
            return
    }

    muroj_after_insert(obj)
}

function muroj_before_insert(content) {
    let jcontent = $(content);
    jcontent.css({'position':'absolute', 'left': "-10000px"});
    $('body').append(jcontent);
    jcontent.css({'max-height': jcontent.outerHeight(), 'position' : '', 'left' : ''})
        .toggleClass('muroj_hidden')
        .detach();
    return jcontent;
}

function muroj_after_insert(obj) {
    obj.find('.aldonu-komento a').on('click', muroj_com_form);
    obj.find('a[data-ago]').on('click', muroj_post);
    obj.find('.interese a').on('click', muroj_interese);
    setTimeout(muroj_toggle_class, 10, obj, 'muroj_hidden');
    setTimeout(function(obj){obj.css('max-height','')}, 2000, obj);
}

function muroj_before_remove(content) {
    let jcontent = $(content);
    jcontent.css({'max-height': jcontent.outerHeight()});
}

function muroj_interese() {
    let target = $(this);
    let loc_kom_type;

    if(typeof kom_type === "undefined") {
        loc_kom_type = target.parents('[data-kom_tipo]').attr('data-kom_tipo');
    } else {
        loc_kom_type = kom_type
    }

    if(typeof intereso_url === "undefined" || typeof loc_kom_type === "undefined") {
        console.log('AJAX Context not found!');
        return;
    }

    target.parents('.interese').find('a').unbind('click', muroj_interese);

    let data = new FormData();
    data.append('enskribo_id', target.parents('div[data-enskribo_id]').attr('data-enskribo_id'));
    data.append('kom_tipo', loc_kom_type);
    data.append('csrfmiddlewaretoken', getCookie('csrftoken'));

    $.ajax({
        url: intereso_url,
        type: 'POST',
        async: true,
        data: data,
        cache: false,
        dataType: 'json',
        processData: false,
        contentType: false
    })
        .done(function (result) {
            if(result.status === 'ok') {
                result.tuta = parseInt(result.tuta) ? result.tuta : '';
                target.parents('.interese')
                    .find('.interese-tuta').text(result.tuta);
                target.parents('.interese')
                    .find('img').attr('src',
                        (result.uzanto_aligis ? '/static/muroj/images/interese_on.png'
                            : '/static/muroj/images/interese.png'));
            } else {
                console.log("Bad server response: " + result.err);
            }
        })
        .fail(function (jqXHR, textStatus) {
            console.log("Request failed: " + textStatus);
        });

    target.parents('.interese')
                    .find('a').on('click', muroj_interese);
}